package com.chenwang.measure.ui.activity;


import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chenwang.measure.MyApp;
import com.chenwang.measure.R;
import com.chenwang.measure.base.BaseActivity;
import com.chenwang.measure.model.ObserverOnNext;
import com.chenwang.measure.receiver.BtReceiver;
import com.chenwang.measure.ui.adapter.BluetoothScanAdapter;
import com.chenwang.measure.utils.BlueConnectTask;
import com.chenwang.measure.utils.MyCrashHandler;
import com.chenwang.measure.utils.MyLogger;
import com.chenwang.measure.utils.MyToast;
import com.chenwang.measure.utils.RxUtils;
import com.chenwang.measure.utils.SharePreferenceUtils;
import com.rxjava.rxlife.RxLife;


import java.io.DataInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;


import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;

//蓝牙
public class BluetoothActivity extends BaseActivity implements BtReceiver.Listener,BaseQuickAdapter.OnItemClickListener {
    @BindView(R.id.iv_on)
    ImageView mIvOn;      //开关
    @BindView(R.id.rv)
    RecyclerView mRv;
    @BindView(R.id.btn_scan)
    Button mBtnScan;      //扫描
    @BindView(R.id.spin_kit)
    ProgressBar mBar;

    private boolean isOnOff;//蓝牙开关
    private List<BluetoothDevice> mDevices;
    private BluetoothAdapter mAdapter; //蓝牙适配器
    private BtReceiver mBtReceiver;     //蓝牙连接监听
    private BluetoothScanAdapter mScanAdapter;//蓝牙列表适配
    private BluetoothDevice mDevice;  //保存最新配对成功的蓝牙设备
    @Override
    public int setLayoutId() {
        return R.layout.activity_bluetooth;
    }

    @Override
    public void initData() {
        super.initData();
        ButterKnife.bind(this);
        mAdapter = BluetoothAdapter.getDefaultAdapter();
        mBtReceiver = new BtReceiver(this, this); //注册蓝牙广播
        initRecycelrView();

    }

    //初始化RecycelrView
    private void initRecycelrView(){
        mRv.setLayoutManager(new LinearLayoutManager(this));
        mScanAdapter = new BluetoothScanAdapter(mDevices);
        mScanAdapter.setOnItemClickListener(this);
        mRv.setAdapter(mScanAdapter);

    }

    //初始化蓝牙开关
    private void initOnOff() {

        if (mAdapter.isEnabled()) {
            isOnOff = true;
            mIvOn.setImageResource(R.mipmap.ic_on);
        } else {
            isOnOff = false;
            mIvOn.setImageResource(R.mipmap.ic_off);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initOnOff();

    }




    @OnClick({R.id.iv_on,R.id.btn_scan})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.iv_on:
                setOnOff();
                break;
            case R.id.btn_scan:
                //扫描蓝牙
                scan();
                break;
        }
    }

     //扫描蓝牙
    private void scan(){

        if (mAdapter.isDiscovering()) {
            mAdapter.cancelDiscovery();
            mBtnScan.setText("开始扫描");
            mBtnScan.setBackgroundResource(R.drawable.corners6_blue);
            mBar.setVisibility(View.INVISIBLE);

        }else {
            mScanAdapter.clear();
            mAdapter.startDiscovery();
            mBtnScan.setText("停止扫描");
            mBtnScan.setBackgroundResource(R.drawable.corners6_red);
            mBar.setVisibility(View.VISIBLE);
        }

    }


    //设置蓝牙开关
    private void setOnOff(){
        if (isOnOff){
            //关
            isOnOff = false;
            mIvOn.setImageResource(R.mipmap.ic_off);
            mAdapter.disable();
            MyToast.show("蓝牙已关闭");
        }else {
            //开
            isOnOff = true;
            mIvOn.setImageResource(R.mipmap.ic_on);
            mAdapter.enable();
            MyToast.show("蓝牙已开启");
        }
    }


    //扫描到的设备
    @Override
    public void foundDev(BluetoothDevice dev) {
        if (!TextUtils.isEmpty(dev.getName())){
            if (mScanAdapter.getData().size() >0){
                boolean is = false ;
                for (int i = 0; i <mScanAdapter.getData().size(); i++){
                    if (mScanAdapter.getData().get(i).getName().equals(dev.getName())){
                        is = true;
                        break;
                    }

                }
                if (!is ){
                    mScanAdapter.addData(dev);
                }
            }else {
                mScanAdapter.addData(dev);
            }


        }
    }
      //扫描完成
    @Override
    public void onScanFinished() {
        mBtnScan.setText("开始扫描");
        mBtnScan.setBackgroundResource(R.drawable.corners6_blue);
        mBar.setVisibility(View.INVISIBLE);
    }

    //配对成功回调
    @Override
    public void onState(int state) {
        if (state == BluetoothDevice.BOND_BONDED){
            MyToast.show("配对成功");
            mScanAdapter.notifyDataSetChanged();
            showNormalDialog();

        }
    }

    //连接成后设为默认连接设备提示框
    private void showNormalDialog(){
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(this);
        normalDialog.setTitle(mDevice.getName()+"");
        normalDialog.setMessage("将此设备作为默认连接");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Set<BluetoothDevice> pairedDevices = mAdapter.getBondedDevices();
                        if (!TextUtils.isEmpty(SharePreferenceUtils.getString(BluetoothActivity.this,"bluetooth_mac" , ""))){
                            for ( BluetoothDevice device: pairedDevices){
                                if (device.getAddress().equals(SharePreferenceUtils.getString(BluetoothActivity.this,"bluetooth_mac" , ""))){
                                    if (!mDevice.getAddress().equals(SharePreferenceUtils.getString(BluetoothActivity.this,"bluetooth_mac" , ""))) {
                                        unpairDevice(device);
                                        SharePreferenceUtils.putString(BluetoothActivity.this, "bluetooth_mac", "");
                                        SharePreferenceUtils.putString(BluetoothActivity.this, "bluetooth_name", "");
                                    }

                                }
                            }
                        }
                        SharePreferenceUtils.putString(BluetoothActivity.this,"bluetooth_mac" , mDevice.getAddress());
                        SharePreferenceUtils.putString( BluetoothActivity.this,"bluetooth_name" , mDevice.getName());
                        finish();

                    }
                });
        normalDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                        dialog.dismiss();
                    }
                });
        // 显示
        normalDialog.show();
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        mDevice = (BluetoothDevice) adapter.getData().get(position);
        try {
                if (mDevice.getBondState() == BluetoothDevice.BOND_NONE) { MyToast.show("正在配对");
                   Method createBondMethod = null;
                   createBondMethod = BluetoothDevice.class.getMethod("createBond");
                   Boolean result = (Boolean) createBondMethod.invoke(mDevice);
                   if (result){
                      // mScanAdapter.notifyDataSetChanged();
                   }else {
                       MyToast.show("配对失败");
                   }
                } else if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED) {
                    MyToast.show("已配对 无需在配对");

                }

        } catch (Exception e) {
            MyToast.show(e.getMessage());
            MyCrashHandler.newInstance().saveCrashInfoToFile(e);
        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBtReceiver);
    }

    /**
     * 移除蓝牙设备
     * @param device  蓝牙设备
     */
    private void unpairDevice(BluetoothDevice device) {
        try {
            Method m = device.getClass()
                    .getMethod("removeBond", (Class[]) null);
            m.invoke(device, (Object[]) null);
        } catch (Exception e) {
            MyToast.show(e.getMessage());
            MyCrashHandler.newInstance().saveCrashInfoToFile(e);
        }
    }



}
